// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.admin.entity.*;
import com.javaweb.admin.mapper.*;
import com.javaweb.admin.query.FormtableMain12083Query;
import com.javaweb.admin.service.IFormtableMain12083Service;
import com.javaweb.admin.vo.formtablemain12083.FormtableMain12083InfoVo;
import com.javaweb.admin.vo.formtablemain12083.FormtableMain12083ListVo;
import com.javaweb.admin.vo.formtablemain12083.FormtableMainQuery;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.common.config.DataSourceType;
import com.javaweb.common.config.DynamicDataSource;
import com.javaweb.common.config.SpecifyDataSource;
import com.javaweb.common.config.UploadFileConfig;
import com.javaweb.common.exception.CustomException;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.GuidCreator;
import com.javaweb.common.utils.JsonResult;
import com.javaweb.common.utils.StringUtils;
import com.javaweb.system.entity.DictData;
import com.javaweb.system.service.IDictDataService;
import com.sphchina.esb.webservice.ISendToReviewLog;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
  * <p>
  * 医疗事业部活动系统 服务类实现
  * </p>
  *
  * @author 鲲鹏
  * @since 2023-06-29
  */
@Service
public class FormtableMain12083ServiceImpl extends BaseServiceImpl<FormtableMain12083Mapper, FormtableMain12083> implements IFormtableMain12083Service {
    private final static String xls = "xls";
    private final static String xlsx = "xlsx";
    private final static String DATE_FORMAT = "yyyy/MM/dd";
    private final static String DATE_FORMAT_HHMMSS = "yyyy-MM-dd HH:mm:ss";

    @Autowired
    private FormtableMain12083Mapper formtableMain12083Mapper;
    @Autowired
    private FormtableMain12083Dt1Mapper formtableMain12083Dt1Mapper;

    @Autowired
    private FormtableMainSalesContractMapper contractMapper;

    @Autowired
    private FormtableMainSalesContractDtlMapper contractDtlMapper;

    @Autowired
    private FormtableMainContractMapMapper contractMapMapper;

    @Autowired
    private FormtableMainSalesPeriodMapper periodMapper;

    @Autowired
    private FormtableMainSalesReturnMapper returnMapper;

    @Autowired
    private IDictDataService dictDataService;

    @Autowired
    private NcPaybillMapper ncPaybillMapper;

    @Autowired
    private NcPaybillDetailMapper ncPaybillDetailMapper;
    @Autowired
    private ISendToReviewLog sendToReviewLog;
    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.BIP)
    public JsonResult getList(BaseQuery query) {
        FormtableMain12083Query formtableMain12083Query = (FormtableMain12083Query) query;
        // 查询条件
        QueryWrapper<FormtableMain12083> queryWrapper = new QueryWrapper<>();
        // queryWrapper.orderByDesc("id");

        // 获取数据列表
        IPage<FormtableMain12083> page = new Page<>(formtableMain12083Query.getPage(), formtableMain12083Query.getLimit());
        IPage<FormtableMain12083> pageData = formtableMain12083Mapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            FormtableMain12083ListVo formtableMain12083ListVo = Convert.convert(FormtableMain12083ListVo.class, x);
            return formtableMain12083ListVo;
        });
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.BIP)
    public JsonResult getMainList(BaseQuery query) {
        FormtableMain12083Query formtableMain12083Query = (FormtableMain12083Query) query;
        // 获取数据列表
        if(formtableMain12083Query.getPage()==null)
        {
            formtableMain12083Query.setPage(1);
            formtableMain12083Query.setLimit(100000);
        }
        IPage<FormtableMain12083ListVo> page = new Page<>(formtableMain12083Query.getPage(), formtableMain12083Query.getLimit());
        IPage<FormtableMain12083ListVo> pageData = formtableMain12083Mapper.getMainList(page, formtableMain12083Query);
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.BIP)
    public JsonResult getOaData(String wxtId , FormtableMainQuery param) {
        IPage<FormtableMain12083ListVo> page = new Page<>(param.getPage(), param.getLimit());
        formtableMain12083Mapper.getOaData(page,wxtId,param);
        return JsonResult.success(page);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SALESFORM)
    public JsonResult uploadSphSalesFile(MultipartFile file, String formPk, String fileId, String ly) {
        if (file == null) {
            return JsonResult.error("上传文件为空");
        }
        String fileDesc = file.getOriginalFilename();
        String suffixName = fileDesc.substring(fileDesc.lastIndexOf("."));//拿到后缀名
        GuidCreator myGUID = new GuidCreator();
        String fileName = myGUID.createNewGuid(GuidCreator.FormatString) + suffixName;
        String absolutePath = new File("").getAbsolutePath();
        String templatePath = absolutePath + UploadFileConfig.uploadFolder;
        templatePath = templatePath.replace('\\', '/');
        String softPath = "/" + ly + "/" + formPk + "/" + fileId;
        templatePath = templatePath + softPath;
        File dests = new File(templatePath);
        File dest = new File(dests, fileName);
        //文件上传-覆盖
        try {
            // 检测是否存在目录
            if (!dests.exists()) {
                dests.mkdirs();
            }
            if (dests.listFiles().length > 0) {
                return JsonResult.error(softPath + "该目录已存在文件");
            }
            file.transferTo(dest);
            //---------------------------------------------
            return JsonResult.success(softPath + "/");//上传成功,文件名以逗号隔开
        } catch (Exception e) {
            return JsonResult.error("上传失败，失败原因[" + fileName + "]：" + e.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SALESFORM)
    public JsonResult submitSphSalesForm(String formType, String body, String ly) {
        if ("contract".equals(formType)) {
            return submitContractForm(body, ly);
        } else if ("period".equals(formType)) {
            return submitPeriodForm(body, ly);
        } else if ("return".equals(formType)) {
            return submitReturnForm(body, ly);
        } else {
            return JsonResult.error("表单类型有误");
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SALESFORM)
    public JsonResult querySphSalesForm(String formType, String formPk, String ly) {
        if ("contract".equals(formType)) {
            FormtableMainSalesContract contract = contractMapper.selectOne(new QueryWrapper<FormtableMainSalesContract>().eq("outpk", formPk).eq("ly", ly));
            FormtableMainSalesContractVo vo = new FormtableMainSalesContractVo();
            BeanUtils.copyProperties(contract,vo);
            return JsonResult.success(vo);
        } else if ("period".equals(formType)) {
            FormtableMainSalesPeriod salesPeriod = periodMapper.selectOne(new QueryWrapper<FormtableMainSalesPeriod>().eq("outpk", formPk).eq("ly", ly));
            FormtableMainSalesPeriodVo vo = new FormtableMainSalesPeriodVo();
            BeanUtils.copyProperties(salesPeriod,vo);
            return JsonResult.success(vo);
        } else if ("return".equals(formType)) {
            FormtableMainSalesReturn salesReturn = returnMapper.selectOne(new QueryWrapper<FormtableMainSalesReturn>().eq("outpk", formPk).eq("ly", ly));
            FormtableMainSalesReturnVo vo = new FormtableMainSalesReturnVo();
            BeanUtils.copyProperties(salesReturn,vo);
            return JsonResult.success(vo);
        } else {
            return JsonResult.error("表单类型有误");
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SALESFORM)
    public JsonResult querySphSalesForms(String formType, List<String> list, String ly) {
        if ("contract".equals(formType)) {
            List<FormtableMainSalesContract> contracts = contractMapper.selectList(new QueryWrapper<FormtableMainSalesContract>().in("outpk", list).eq("ly", ly));
            if (CollectionUtils.isEmpty(contracts)) {
                return JsonResult.success();
            }
            List<FormtableMainSalesContractVo> contractVos = new ArrayList<>();
            for (FormtableMainSalesContract contract : contracts) {
                FormtableMainSalesContractVo vo = new FormtableMainSalesContractVo();
                BeanUtils.copyProperties(contract,vo);
                contractVos.add(vo);
            }
            return JsonResult.success(contractVos);
        } else if ("period".equals(formType)) {
            List<FormtableMainSalesPeriod> salesPeriods = periodMapper.selectList(new QueryWrapper<FormtableMainSalesPeriod>().in("outpk", list).eq("ly", ly));
            if (CollectionUtils.isEmpty(salesPeriods)) {
                return JsonResult.success();
            }
            List<FormtableMainSalesPeriodVo> salesPeriodVos = new ArrayList<>();
            for (FormtableMainSalesPeriod period : salesPeriods) {
                FormtableMainSalesPeriodVo vo = new FormtableMainSalesPeriodVo();
                BeanUtils.copyProperties(period,vo);
                salesPeriodVos.add(vo);
            }
            return JsonResult.success(salesPeriodVos);
        } else if ("return".equals(formType)) {
            List<FormtableMainSalesReturn> salesReturns = returnMapper.selectList(new QueryWrapper<FormtableMainSalesReturn>().in("outpk", list).eq("ly", ly));
            if (CollectionUtils.isEmpty(salesReturns)) {
                return JsonResult.success();
            }
            List<FormtableMainSalesReturnVo> salesReturnVos = new ArrayList<>();
            for (FormtableMainSalesReturn salesReturn : salesReturns) {
                FormtableMainSalesReturnVo vo = new FormtableMainSalesReturnVo();
                BeanUtils.copyProperties(salesReturn,vo);
                salesReturnVos.add(vo);
            }
            return JsonResult.success(salesReturnVos);
        } else {
            return JsonResult.error("表单类型有误");
        }
    }



    private JsonResult submitReturnForm(String body, String ly) {
        try {
            FormtableMainSalesReturnDto dto = JSON.parseObject(body, FormtableMainSalesReturnDto.class);
            FormtableMainSalesReturn newSalesReturn = new FormtableMainSalesReturn();
            BeanUtils.copyProperties(dto, newSalesReturn);
            FormtableMainSalesReturn oldSalesReturn = returnMapper.selectOne(new QueryWrapper<FormtableMainSalesReturn>().eq("outpk", dto.getOutpk()).eq("ly", ly));
            if (oldSalesReturn != null) {
                if (!"0".equals(oldSalesReturn.getFtriggerflag())) {
                    return JsonResult.error("oa已读取无法更新");
                } else {
                    newSalesReturn.setId(newSalesReturn.getId());
                    returnMapper.updateById(newSalesReturn);
                }
            } else {
                returnMapper.insert(newSalesReturn);
            }
        } catch (BeansException e) {
            JsonResult.error("系统错误");
        }
        return JsonResult.success();
    }

    private JsonResult submitPeriodForm(String body, String ly) {
        try {
            FormtableMainSalesPeriodDto dto = JSON.parseObject(body, FormtableMainSalesPeriodDto.class);
            FormtableMainSalesPeriod newSalesPeriod = new FormtableMainSalesPeriod();
            BeanUtils.copyProperties(dto, newSalesPeriod);
            FormtableMainSalesPeriod oldSalesPeriod = periodMapper.selectOne(new QueryWrapper<FormtableMainSalesPeriod>().eq("outpk", dto.getOutpk()).eq("ly", ly));
            if (oldSalesPeriod != null) {
                if (!"0".equals(oldSalesPeriod.getFtriggerflag())) {
                    return JsonResult.error("oa已读取无法更新");
                } else {
                    newSalesPeriod.setId(newSalesPeriod.getId());
                    periodMapper.updateById(newSalesPeriod);
                }
            } else {
                periodMapper.insert(newSalesPeriod);
            }
        } catch (BeansException e) {
            JsonResult.error("系统错误");
        }
        return JsonResult.success();
    }

    public JsonResult submitContractForm(String body, String ly) {
        try {
            FormtableMainSalesContractDto dto = JSON.parseObject(body, FormtableMainSalesContractDto.class);
            checkContractForm(dto);
            buildContractForm(dto);
            FormtableMainSalesContract oldContract = contractMapper.selectOne(new QueryWrapper<FormtableMainSalesContract>().eq("outpk", dto.getCsourcebillid()).eq("ly", ly));
            if (oldContract != null) {
                if (!"0".equals(oldContract.getFtriggerflag())) {
                    return JsonResult.error("oa已读取无法更新");
                } else {
                    FormtableMainSalesContract newSalesContract = new FormtableMainSalesContract();
                    BeanUtils.copyProperties(dto, newSalesContract);
                    newSalesContract.setId(oldContract.getId());
                    newSalesContract.setOutpk(newSalesContract.getCsourcebillid());
                    newSalesContract.setRestjson(body);
                    contractMapper.updateById(newSalesContract);
                    contractDtlMapper.delete(new QueryWrapper<FormtableMainSalesContractDtl>().eq("pid", oldContract.getId()));
                    List<FormtableMainSalesContractDtlDto> details = dto.getFormDetails();
                    if (!CollectionUtils.isEmpty(details)) {
                        for (FormtableMainSalesContractDtlDto detail : details) {
                            FormtableMainSalesContractDtl contractDtl = new FormtableMainSalesContractDtl();
                            BeanUtils.copyProperties(detail, contractDtl);
                            contractDtl.setPid(oldContract.getId());
                            contractDtlMapper.insert(contractDtl);
                        }
                    }
                    return JsonResult.success("更新成功");
                }
            } else {
                FormtableMainSalesContract salesContract = new FormtableMainSalesContract();
                BeanUtils.copyProperties(dto, salesContract);
                salesContract.setOutpk(salesContract.getCsourcebillid());
                salesContract.setLy(ly);
                salesContract.setRestjson(body);
                contractMapper.insert(salesContract);
                FormtableMainSalesContract contract = contractMapper.selectOne(new QueryWrapper<FormtableMainSalesContract>().eq("outpk", dto.getOutpk()).eq("ly", ly));
                List<FormtableMainSalesContractDtlDto> details = dto.getFormDetails();
                if (!CollectionUtils.isEmpty(details)) {
                    for (FormtableMainSalesContractDtlDto detail : details) {
                        FormtableMainSalesContractDtl contractDtl = new FormtableMainSalesContractDtl();
                        BeanUtils.copyProperties(detail, contractDtl);
                        contractDtl.setPid(contract.getId());
                        contractDtlMapper.insert(contractDtl);
                    }
                }
            }

        }catch (CustomException e) {
           return JsonResult.error(e.getMessage());
        } catch (BeansException e) {
            return JsonResult.error("系统错误");
        }catch (RuntimeException e){
            return JsonResult.error(e.getCause());
        }
        return JsonResult.success();
    }

    private void buildContractForm(FormtableMainSalesContractDto dto) {
        //管理属性
        String glsx = dto.getGlsx();
        //是否重大合同
        Boolean isImportant = false;
        HashSet<String> glsxSet1 = new HashSet<>();
        glsxSet1.add("A5-1-代理合同-总代、省代");
        glsxSet1.add("B4-代理合同");
        glsxSet1.add("B5-CSO协议");
        glsxSet1.add("C1-资产管理类合同");
        glsxSet1.add("C2-知识产权类合同");
        glsxSet1.add("C3-金融类合同");
        glsxSet1.add("D1-工程项目类合同");
        glsxSet1.add("E1-科研类合同");
        glsxSet1.add("E2-广告类合同");
        HashSet<String> glsxSet2 = new HashSet<>();
        glsxSet2.add("D2-1-设备设施类合同-IT类");
        glsxSet2.add("D2-2-设备设施类合同-物流类");
        glsxSet2.add("D2-3-设备设施类合同-办公类");
        glsxSet2.add("E3-服务类合同");
        HashSet<String> glsxSet3 = new HashSet<>();
        glsxSet3.add("A1-一级商协议");
        glsxSet3.add("A2-二级商协议");
        glsxSet3.add("A3-批次订单");
        glsxSet3.add("A4-返利协议");
        glsxSet3.add("A6-CSO协议");
        glsxSet3.add("A7-劳务协议");
        glsxSet3.add("B1-采购合同");
        glsxSet3.add("B2-批次订单");
        glsxSet3.add("B3-返利协议");
        BigDecimal amount50 = new BigDecimal("500000");
        HashMap<String, String> buLeaderMap = new HashMap<>();
        buLeaderMap.put("上海医药集团工业营销管理有限公司","");
        buLeaderMap.put("上海医药集团药品销售有限公司","刘英");
        buLeaderMap.put("上海信谊联合医药药材有限公司","朱蕾");
        buLeaderMap.put("上海信谊天一药业有限公司","移传萍");
        buLeaderMap.put("上海上柯医药有限公司","吕大岩");
        buLeaderMap.put("上海上药新亚医药有限公司","杨春");
        buLeaderMap.put("上海上药龙虎医药销售有限公司","杨毓方");
        buLeaderMap.put("上海信谊联合医药药材有限公司信谊医药事业部","唐湧");
        if (glsxSet1.contains(glsx)) {
            isImportant = true;
        } else if (glsxSet2.contains(glsx)) {
            isImportant = new BigDecimal(dto.getA14()).compareTo(amount50) >= 0;
        } else if (glsxSet3.contains(glsx)) {
            isImportant = new BigDecimal(dto.getA14()).compareTo(amount50) >= 0 && ("有模板未使用".equals(dto.getA234()) || "无模板".equals(dto.getA234()));
        }
        List<FormtableMainContractMap> contractMapList = contractMapMapper.selectList(new QueryWrapper<FormtableMainContractMap>().eq("oa_manage_attribute", dto.getGlsx()));
        FormtableMainContractMap contractMap = null;
        if (!CollectionUtils.isEmpty(contractMapList)) {
            contractMap = contractMapList.get(0);
        }else {
            throw new CustomException("该合同没有做管理属性与合同审级映射，glsx :" + dto.getGlsx());
        }
        //是否天一、医药
        Boolean isTyYy = "上海信谊天一药业有限公司".equals(dto.getA4())||"上海信谊联合医药药材有限公司信谊医药事业部".equals(dto.getA4());

        if (isImportant) {
            if (isTyYy) {
                dto.setA2(contractMap.getCommonLevel2());
            }else {
                dto.setA2(contractMap.getCommonLevel3());
            }
        } else {
                dto.setA2(contractMap.getCommonLevel1());
        }
        if ("BU总经理".equals(contractMap.getAuthorizer())) {
            dto.setQysqr(buLeaderMap.get(dto.getA4()));
        }else {
            dto.setQysqr(contractMap.getAuthorizer());
        }

    }

    private void checkContractForm(FormtableMainSalesContractDto dto) {

        if (StringUtils.isEmpty(dto.getA4())) {
            throw new CustomException("我方名称为空");
        }
        String code = dictDataService.getCodeByName("FORM_TABLE", dto.getA4());
        HashMap<String,DictData> cache = dictDataService.getFormCache("FORM_TABLE");
        DynamicDataSource.setDataSource(DataSourceType.SALESFORM.getName());
        checkField(cache,dto.getA4(),"a4","我方名称");
        checkField(cache, dto.getGlsx(), "glsx", "管理属性");
        checkField(cache, dto.getHtlx(), "htlx", "合同类型");
        checkField(cache, dto.getA30(), "a30", "合同类别（大类）");
        checkField(cache, dto.getA1(), "a1", "合同类别（小类）");
        checkField(cache, dto.getA23(), "a23", "合同分类");
        checkField(cache, dto.getA26(), "a26", "争议解决方式");
        checkField(cache, dto.getA15(), "a15", "币种");
        checkField(cache, dto.getD15(), "d15", "是否固定标的金额付款合同");
        checkField(cache, dto.getHtxz(), "htxz", "合同性质");
        checkField(cache, dto.getLxqx(), "lxqx", "合同期限");
        checkField(cache, dto.getA234(), "a234", "格式合同使用情况");
        checkField(cache, dto.getA27(), "a27", "生效要件（选项）");
        checkField(cache, dto.getYyfs(), "yyfs", "用印方式");
        if (StringUtils.isEmpty(dto.getA14())) {
            throw new CustomException("a14 标的金额为空");
        }
        dto.setWfmc(code);
        if (StringUtils.isEmpty(dto.getCsourcebillid())) {
            throw new CustomException("主键为空");
        }

    }

    private void checkField(HashMap<String, DictData> cache, String field, String msg, String dictType) {
        if (StringUtils.isEmpty(field) || !cache.containsKey(dictType + field)) {
            throw new CustomException("字段" + msg + "不规范或为空");
        }
    }

    private String CheckMainData(FormtableMain12083 mainEntity)
    {
        StringBuilder sb = new StringBuilder();
        if(StringUtils.isEmpty(mainEntity.getWxtbh()))
        {
            sb.append("外系统编号:wxtbh值为空，请确保将系统中的唯一主键作为外系统编号。");
        }
        if(StringUtils.isEmpty(mainEntity.getWxtId()))
        {
            sb.append("外系统ID:wxtID值为空，请联系接口提供方获取外系统ID。");
        }
        if(StringUtils.isEmpty(mainEntity.getHtlx()))
        {
            sb.append("合同类型:htlx值为空，请联系接口提供方获取合同类型代码。");
        }

        return sb.toString();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.BIP)
    public JsonResult Create(String body) {
        try {
            FormTableMainDto dto = JSON.parseObject(body, FormTableMainDto.class);
            if (dto != null) {
                //判断OA读取状态
                FormtableMain12083 mainEntity = dto.getFormtableMain();
                FormtableMain12083ListVo entity = formtableMain12083Mapper.GetEntity(mainEntity.getWxtbh(),mainEntity.getWxtId());
                //判断外部系统编号是否已经开通
                DynamicDataSource.setDataSource("system");
                if(!isExistsWxtbh(mainEntity.getWxtId()))
                {
                    return JsonResult.error("外系统编号："+mainEntity.getWxtId()+"未开通，无法提交数据");
                }
                DynamicDataSource.setDataSource("bip");

                if(entity!=null && "1".equals(entity.getFtriggerflag()))
                {
                    return JsonResult.error("外系统编号："+mainEntity.getWxtbh()+" OA流程ID:"+entity.getRequestid()+",OA系统已读取，无法再次提交。");
                }
                String checkResult = CheckMainData(mainEntity);
                if (!StringUtils.isEmpty(checkResult)) {
                    return JsonResult.error(checkResult);
                }
                if(entity!=null)
                {
                    Map<String, Object> param = new HashMap<>();
                    param.put("wxtbh", mainEntity.getWxtbh());
                    param.put("wxt_id", mainEntity.getWxtId());

                    formtableMain12083Mapper.deleteByMap(param);
                    param.clear();
                    param.put("parent_id", entity.getId());

                    formtableMain12083Dt1Mapper.deleteByMap(param);
                }
                String A31 = "/"+mainEntity.getWxtId()+"/"+mainEntity.getWxtbh()+"/body/";
                mainEntity.setA31(A31);
                formtableMain12083Mapper.insert(mainEntity);
                for (FormtableMain12083Dt1 item : dto.getFormtableDetails()) {
                    item.setParentId(mainEntity.getId());
                    //附件目录
                    if (!StringUtils.isEmpty(item.getDtWxtbh())) {
                        item.setNjyyzz(A31 + item.getDtWxtbh() + "/");
                    }
                    formtableMain12083Dt1Mapper.insert(item);
                }

                return JsonResult.success("数据提交成功。");
            } else {
                return JsonResult.error("提交数据出错，请检查提交数据格式。");
            }
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }


    public static Workbook getWorkBook(MultipartFile file) {
        //获得文件名
        String fileName = file.getOriginalFilename();
        //创建Workbook工作薄对象，表示整个excel
        Workbook workbook = null;
        try {
            //获取excel文件的io流
            InputStream is = file.getInputStream();
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if(fileName.endsWith(xls)){
                //2003
                workbook = new HSSFWorkbook(is);
            }else if(fileName.endsWith(xlsx)){
                //2007
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }
    public static String getCellValue(Cell cell){
        String cellValue = "";
        if(cell == null){
            return cellValue;
        }
        //如果当前单元格内容为日期类型，需要特殊处理
        String dataFormatString = cell.getCellStyle().getDataFormatString();
        if(dataFormatString.equals("yyyy\\-mm\\-dd\\ hh:mm:ss")){
            cellValue = new SimpleDateFormat(DATE_FORMAT_HHMMSS).format(cell.getDateCellValue());
            return cellValue;
        }
        //把数字当成String来读，避免出现1读成1.0的情况
        if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        //判断数据的类型
        switch (cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC: //数字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

    @Override
    public JsonResult importYJ(MultipartFile file) {
        String message = "";
        StringBuilder sb = new StringBuilder();

        try {
            Workbook workbook = getWorkBook(file);

            if (workbook != null) {
                // for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                //获得当前sheet工作表
                Sheet sheet = workbook.getSheetAt(0);

                //获得当前sheet的开始行
                int firstRowNum = sheet.getFirstRowNum();
                //获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();

                //循环所有行
                Integer rowIndex = 0;
                String billclass = getCellValue(sheet.getRow(2).getCell(2)).toLowerCase();
                if("fk".equals(billclass)) {
                    for (int rowNum = 2; rowNum <= lastRowNum; rowNum++) {
                        //获得当前行
                        Row row = sheet.getRow(rowNum);
                        if (row == null) {
                            rowIndex = rowNum + 3;
                            break;
                        }
                        //获得当前行的开始列
                        int firstCellNum = row.getFirstCellNum();
                        //获得当前行的列数
                        int lastCellNum = row.getPhysicalNumberOfCells();
                        NcPaybill entity = new NcPaybill();
                        //循环当前行
                        String cellValue = "";
                        String id = getCellValue(row.getCell(1));
                        if (StringUtils.isEmpty(id)) {
                            //id为空，主表处理结束，开始处理明细
                            rowIndex = rowNum + 3;
                            break;
                        }

                        for (int cellNum = 1; cellNum < 29; cellNum++) {
                            Cell cell = row.getCell(cellNum);
                            cellValue = getCellValue(cell);

                            switch (cellNum) {
                                case 1: //手工码
                                    id = cellValue;
                                    entity.setId(Integer.valueOf(cellValue));
                                    // Material=  getList(material);
                                    break;
                                case 2: //单据大类
                                    entity.setBillclass(cellValue);
                                    break;
                                case 3: //单据日期
                                    entity.setBilldate(cellValue);
                                    break;
                                case 4: //制单人
                                    entity.setBillmaker(cellValue);
                                    break;
                                case 5: //付款单据号
                                    entity.setBillno(cellValue);
                                    break;
                                case 6: //单据状态
                                    entity.setBillstatus(cellValue);
                                    break;
                                case 7: //品牌
                                    entity.setBusidate(cellValue);
                                    break;
                                case 8: //用途
                                    entity.setCreationtime(cellValue);
                                    break;
                                case 9: //净重
                                    entity.setCreator(cellValue);
                                    break;
                                case 10: //皮重
                                    entity.setDef1(cellValue);
                                    break;
                                case 11: //ABC
                                    entity.setDef27(cellValue);
                                    break;
                                case 12: //单位重量
                                    entity.setDef28(cellValue);
                                    break;
                                case 13: //单位重量
                                    entity.setFkyt(cellValue);
                                    break;
                                case 14: //单位重量
                                    entity.setLocalMoney(cellValue);
                                    break;
                                case 15: //单位重量
                                    entity.setMoney(cellValue);
                                    break;
                                case 16: //单位重量
                                    entity.setObjtype(cellValue);
                                    break;
                                case 17: //单位重量
                                    entity.setPayaccount(cellValue);
                                    break;
                                case 18: //单位重量
                                    entity.setPkBalatype(cellValue);
                                    break;
                                case 19: //单位重量
                                    entity.setPkBusitype(cellValue);
                                    break;
                                case 20: //单位重量
                                    entity.setPkCurrtype(cellValue);
                                    break;
                                case 21: //单位重量
                                    entity.setPkDeptid(cellValue);
                                    break;
                                case 22: //单位重量
                                    entity.setPkGroup(cellValue);
                                    break;
                                case 23: //单位重量
                                    entity.setPkOrg(cellValue);
                                    break;
                                case 24: //单位重量
                                    entity.setPkPsndoc(cellValue);
                                    break;
                                case 25: //单位重量
                                    entity.setPkTradetype(cellValue);
                                    break;
                                case 26: //单位重量
                                    entity.setRate(cellValue);
                                    break;
                                case 27: //单位重量
                                    entity.setRecaccount(cellValue);
                                    break;
                                case 28: //单位重量
                                    entity.setSupplier(cellValue);
                                    break;
                            }
                        }
                        try {
                            entity.setDef1(entity.getPkOrg() + entity.getBillno());
                            ncPaybillMapper.insert(entity);
                        } catch (Exception ex) {
                            return JsonResult.error(ex.getCause().getMessage());
                        }
                    }
                    for (int rowNum = rowIndex; rowNum <= lastRowNum; rowNum++) {
                        //获得当前行
                        Row row = sheet.getRow(rowNum);
                        if (row == null) {
                            continue;
                        }
                        //获得当前行的开始列
                        int firstCellNum = row.getFirstCellNum();
                        //获得当前行的列数
                        int lastCellNum = row.getPhysicalNumberOfCells();
                        NcPaybillDetail entity = new NcPaybillDetail();
                        //循环当前行
                        String cellValue = "";
                        String id = "";

                        for (int cellNum = 1; cellNum < 22; cellNum++) {
                            Cell cell = row.getCell(cellNum);
                            cellValue = getCellValue(cell);

                            switch (cellNum) {
                                case 1: //手工码
                                    id = cellValue;
                                    entity.setPid(Integer.valueOf(cellValue));
                                    // Material=  getList(material);
                                    break;
                                case 2: //单据大类
                                    entity.setPayaccount(cellValue);
                                    break;
                                case 3: //单据日期
                                    entity.setRecaccount(cellValue);
                                    break;
                                case 4: //制单人
                                    entity.setScomment(cellValue);
                                    break;
                                case 5: //付款单据号
                                    entity.setObjtype(cellValue);
                                    break;
                                case 6: //单据状态
                                    entity.setSupplier(cellValue);
                                    break;
                                case 7: //品牌
                                    entity.setPkDeptid(cellValue);
                                    break;
                                case 8: //用途
                                    entity.setPkPsndoc(cellValue);
                                    break;
                                case 9: //净重
                                    entity.setLocalMoneyDe(cellValue);
                                    break;
                                case 10: //皮重
                                    entity.setMoneyDe(cellValue);
                                    break;
                                case 11: //皮重
                                    entity.setRowno(Integer.valueOf(cellValue));
                                    break;
                                case 12: //ABC
                                    entity.setCreator(cellValue);
                                    break;
                                case 13: //单位重量
                                    entity.setCreationtime(cellValue);
                                    break;
                                case 14: //单位重量
                                    entity.setTaxrate(cellValue);
                                    break;
                                case 15: //单位重量
                                    entity.setDef20(cellValue);
                                    break;
                                case 16: //单位重量
                                    entity.setLocalTaxDe(cellValue);
                                    break;
                                case 17: //单位重量
                                    entity.setHxdydjh(cellValue);
                                    break;
                                case 18: //单位重量
                                    entity.setHxje(cellValue);
                                    break;
                                case 19: //单位重量
                                    entity.setHh(cellValue);
                                    break;
                                case 20: //单位重量
                                    entity.setSfzdhx(cellValue);
                                    break;
                                case 21: //单位重量
                                    entity.setDef24(cellValue);
                                    break;
                            }
                        }
                        try {
                            ncPaybillDetailMapper.insert(entity);
                        } catch (Exception ex) {
                            return JsonResult.error(ex.getCause().getMessage());
                        }
                        if (StringUtils.isEmpty(id)) {
                            //id为空，主表处理结束，开始处理明细
                            break;
                        }
                    }
                }
                else if("yf".equals(billclass))
                {
                    for (int rowNum = 2; rowNum <= lastRowNum; rowNum++) {
                        //获得当前行
                        Row row = sheet.getRow(rowNum);
                        if (row == null) {
                            rowIndex = rowNum + 3;
                            break;
                        }
                        //获得当前行的开始列
                        int firstCellNum = row.getFirstCellNum();
                        //获得当前行的列数
                        int lastCellNum = row.getPhysicalNumberOfCells();
                        NcPaybill entity = new NcPaybill();
                        //循环当前行
                        String cellValue = "";
                        String id = getCellValue(row.getCell(1));
                        if (StringUtils.isEmpty(id)) {
                            //id为空，主表处理结束，开始处理明细
                            rowIndex = rowNum + 3;
                            break;
                        }
                        //判断手工码是否存在
                        Map<String,Object> param = new HashMap<>();
                        param.put("id",id);
                        List<NcPaybill> paybills= ncPaybillMapper.selectByMap(param);
                        if(paybills.size()>0)
                        {
                            sb.append("手工码"+id+"对应的单据号："+getCellValue(row.getCell(5))+"已存在，请检查导入文件。");
                            continue;
                        }

                        for (int cellNum = 1; cellNum < 33; cellNum++) {
                            Cell cell = row.getCell(cellNum);
                            cellValue = getCellValue(cell);

                            switch (cellNum) {
                                case 1: //手工码
                                    id = cellValue;
                                    entity.setId(Integer.valueOf(cellValue));
                                    // Material=  getList(material);
                                    break;
                                case 2: //单据大类
                                    entity.setBillclass(cellValue);
                                    break;
                                case 3: //单据日期
                                    entity.setBilldate(cellValue);
                                    break;
                                case 4: //制单人
                                    entity.setBillmaker(cellValue);
                                    break;
                                case 5: //付款单据号
                                    entity.setBillno(cellValue);
                                    break;
                                case 6: //单据状态
                                    entity.setBillstatus(cellValue);
                                    break;
                                case 7: //品牌
                                    entity.setBusidate(cellValue);
                                    break;
                                case 8: //用途
                                    entity.setCreationtime(cellValue);
                                    break;
                                case 9: //净重
                                    entity.setCreator(cellValue);
                                    break;
                                case 10: //皮重
                                    entity.setDef1(cellValue);
                                    break;
                                case 11: //ABC
                                    entity.setDef27(cellValue);
                                    break;
                                case 12: //单位重量
                                    entity.setFkyt(cellValue);
                                    break;
                                case 13: //单位重量
                                    entity.setLocalMoney(cellValue);
                                    break;
                                case 14: //单位重量
                                    entity.setMoney(cellValue);
                                    break;
                                case 15: //单位重量
                                    entity.setObjtype(cellValue);
                                    break;
                                case 16: //单位重量
                                    entity.setPayaccount(cellValue);
                                    break;
                                case 17: //单位重量
                                    entity.setPkBalatype(cellValue);
                                    break;
                                case 18: //单位重量
                                    entity.setPkBusitype(cellValue);
                                    break;
                                case 19: //单位重量
                                    entity.setPkCurrtype(cellValue);
                                    break;
                                case 20: //单位重量
                                    entity.setPkDeptid(cellValue);
                                    break;
                                case 21: //单位重量
                                    entity.setPkGroup(cellValue);
                                    break;
                                case 22: //单位重量
                                    entity.setPkOrg(cellValue);
                                    break;
                                case 23: //单位重量
                                    entity.setPkPsndoc(cellValue);
                                    break;
                                case 24: //单位重量
                                    entity.setPkTradetype(cellValue);
                                    break;
                                case 25: //单位重量
                                    entity.setRate(cellValue);
                                    break;
                                case 26: //单位重量
                                    entity.setRecaccount(cellValue);
                                    break;
                                case 27: //单位重量
                                    entity.setSupplier(cellValue);
                                    break;
                                case 28: //单位重量
                                    entity.setDef12(cellValue);
                                    break;
                                case 29: //单位重量
                                    entity.setHxje(cellValue);
                                    break;
                                case 30: //单位重量
                                    entity.setDef24(cellValue);
                                    break;
                                case 31: //单位重量
                                    entity.setDef29(cellValue);
                                    break;
                                case 32: //单位重量
                                    entity.setDef25(cellValue);
                                    break;
                            }
                        }
                        try {
                            entity.setDef1(entity.getPkOrg() + entity.getBillno());
                            ncPaybillMapper.insert(entity);
                        } catch (Exception ex) {
                            return JsonResult.error(ex.getCause().getMessage());
                        }
                    }
                    for (int rowNum = rowIndex; rowNum <= lastRowNum; rowNum++) {
                        //获得当前行
                        Row row = sheet.getRow(rowNum);
                        if (row == null) {
                            continue;
                        }
                        //获得当前行的开始列
                        int firstCellNum = row.getFirstCellNum();
                        //获得当前行的列数
                        int lastCellNum = row.getPhysicalNumberOfCells();
                        NcPaybillDetail entity = new NcPaybillDetail();
                        //循环当前行
                        String cellValue = "";
                        String id = getCellValue(row.getCell(1));
                        if(StringUtils.isEmpty(id) || "手工码".equals(id))
                        {
                            continue;
                        }
                        Map<String,Object> param = new HashMap<>();
                        param.put("pid",id);
                        List<NcPaybillDetail> paybills= ncPaybillDetailMapper.selectByMap(param);
                        if(paybills.size()>0)
                        {
                            //sb.append("手工码"+id+"对应的单据号："+getCellValue(row.getCell(5))+"已存在，请检查导入文件。");
                            //continue;
                        }

                        for (int cellNum = 1; cellNum < 25; cellNum++) {
                            Cell cell = row.getCell(cellNum);
                            cellValue = getCellValue(cell);

                            switch (cellNum) {
                                case 1: //手工码
                                    id = cellValue;
                                    entity.setPid(Integer.valueOf(cellValue));
                                    // Material=  getList(material);
                                    break;
                                case 2: //单据大类
                                    entity.setPayaccount(cellValue);
                                    break;
                                case 3: //单据日期
                                    entity.setRecaccount(cellValue);
                                    break;
                                case 4: //制单人
                                    entity.setScomment(cellValue);
                                    break;
                                case 5: //付款单据号
                                    entity.setObjtype(cellValue);
                                    break;
                                case 6: //单据状态
                                    entity.setSupplier(cellValue);
                                    break;
                                case 7: //品牌
                                    entity.setPkDeptid(cellValue);
                                    break;
                                case 8: //用途
                                    entity.setPkPsndoc(cellValue);
                                    break;
                                case 9: //净重
                                    entity.setLocalMoneyDe(cellValue);
                                    break;
                                case 10: //皮重
                                    entity.setMoneyDe(cellValue);
                                    break;
                                case 11: //皮重
                                    entity.setRowno(Integer.valueOf(cellValue));
                                    break;
                                case 12: //ABC
                                    entity.setCreator(cellValue);
                                    break;
                                case 13: //单位重量
                                    entity.setCreationtime(cellValue);
                                    break;
                                case 15: //单位重量
                                    entity.setInvoiceno(cellValue);
                                    break;
                                case 16: //单位重量
                                    entity.setCaltaxmny(cellValue);
                                    break;
                                case 17: //单位重量
                                    entity.setLocalTaxCr(cellValue);
                                    break;
                                case 18: //单位重量
                                    entity.setTaxrate(cellValue);
                                    break;
                                case 20: //单位重量
                                    entity.setDef28(cellValue);
                                    break;
                                case 21: //单位重量
                                    entity.setDef25(cellValue);
                                    break;
                                case 22: //单位重量
                                    entity.setDef30(cellValue);
                                    break;
                                case 23: //单位重量
                                    entity.setDef20(cellValue);
                                    break;
                                case 24: //单位重量
                                    entity.setDef24(cellValue);
                                    break;
                            }
                        }
                        try {
                            ncPaybillDetailMapper.insert(entity);
                        } catch (Exception ex) {
                            return JsonResult.error(ex.getCause().getMessage());
                        }
                        if (StringUtils.isEmpty(id)) {
                            //id为空，主表处理结束，开始处理明细
                            break;
                        }
                    }

                }
            }
            workbook.close();
            // }
            message =StringUtils.isEmpty(sb.toString())?"导入成功！":sb.toString();
            sendToReviewLog.sendFKOrder();
            sendToReviewLog.sendYFOrder();
            return JsonResult.success(message);
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }

    }

    @Override
    public JsonResult uploadFile(MultipartFile file, String documentId, String getFromFile){
        String fileDesc = file.getOriginalFilename();
        String suffixName=fileDesc.substring(fileDesc.lastIndexOf("."));//拿到后缀名
        GuidCreator myGUID = new GuidCreator();
        String fileName=myGUID.createNewGuid(GuidCreator.FormatString);
        fileName=fileName+suffixName;
        if (org.springframework.util.StringUtils.isEmpty(fileName)) {
            return JsonResult.success("上传文件为空");
        }
        File filePath = new File("");
        //当前项目下路径+静态资源实际存储路径
        String path=filePath.getAbsolutePath();
        String templatePath = path+ UploadFileConfig.uploadFolder;
        templatePath=templatePath.replace('\\','/');
        templatePath+=documentId;
        File dests = new File(templatePath);
        File dest = new File(dests, fileName);
        //文件上传-覆盖
        try {
            // 检测是否存在目录
            if(!dests.exists()){
                dests.mkdirs();
            }
            // getParentFile获取上一级
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);

            //插入数据到file_info-----------------
//            List<SuppfileInfo> list=getFileInfoListByWhere(documentId,fileName,getFromFile);
//            if(list.size()<=0){
//                SuppfileInfo fi=new SuppfileInfo();
//                String fileUrl= UploadFileConfig.accessFilePath+fileName;
//                fi.setFilePath(fileUrl);//获取配置文件中的相对路径
//                fi.setFileName(fileName);//guid+后缀名
//                fi.setFileDesc(fileDesc);//文件描述=文件名
//                fi.setDocumentId(documentId);//关联主表id
//                fi.setGetFromFile(getFromFile); //附件主表
//                edit(fi);
//            }
            //---------------------------------------------
            return JsonResult.success(fileName+",");//上传成功,文件名以逗号隔开
        } catch (Exception e) {
            return JsonResult.error("上传失败，失败原因["+documentId+"]："+e.getMessage());
        }
    }


    @Override
    public JsonResult uploadOaFile(MultipartFile file, String wxtid, String wxtbh, String fileid) {
        DynamicDataSource.setDataSource("system");
        if (!isExistsWxtbh(wxtid)) {
            return JsonResult.error("外系统编号：" + wxtid + "未开通，无法提交数据");
        }
        DynamicDataSource.setDataSource("bip");
        if (file == null) {
            return JsonResult.error("上传文件为空");
        }

        String fileDesc = file.getOriginalFilename();
        String suffixName = fileDesc.substring(fileDesc.lastIndexOf("."));//拿到后缀名
        GuidCreator myGUID = new GuidCreator();
        String fileName = myGUID.createNewGuid(GuidCreator.FormatString) + suffixName;
        //当前项目下路径+静态资源实际存储路径
        String absolutePath = new File("").getAbsolutePath();
        String templatePath = absolutePath + UploadFileConfig.uploadFolder;
        templatePath = templatePath.replace('\\', '/');
        String softPath = "/" + wxtid + "/" + wxtbh + "/" + fileid;
        templatePath = templatePath + softPath;
        File dests = new File(templatePath);
        File dest = new File(dests, fileName);
        //文件上传-覆盖
        try {
            // 检测是否存在目录
            if (!dests.exists()) {
                dests.mkdirs();
            }
            if (dests.listFiles().length > 0) {
                return JsonResult.error(softPath + "该目录已存在文件");
            }
            file.transferTo(dest);
            //---------------------------------------------
            return JsonResult.success(fileName + ",");//上传成功,文件名以逗号隔开
        } catch (Exception e) {
            return JsonResult.error("上传失败，失败原因[" + fileName + "]：" + e.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.BIP)
    public JsonResult submitOaData(String body) {
        try {
            FormTableMainDto dto = JSON.parseObject(body, FormTableMainDto.class);
            if (dto != null) {
                //判断OA读取状态
                FormtableMain12083 mainEntity = dto.getFormtableMain();
                FormtableMain12083ListVo entity = formtableMain12083Mapper.GetEntity(mainEntity.getWxtbh(), mainEntity.getWxtId());
                //判断外部系统编号是否已经开通
                DynamicDataSource.setDataSource("system");
                if (!isExistsWxtbh(mainEntity.getWxtId())) {
                    return JsonResult.error("外系统编号：" + mainEntity.getWxtId() + "未开通，无法提交数据");
                }
                DynamicDataSource.setDataSource("bip");
                if (entity != null && "1".equals(entity.getFtriggerflag())) {
                    return JsonResult.error("外系统编号：" + mainEntity.getWxtbh() + " OA流程ID:" + entity.getRequestid() + ",OA系统已读取，无法再次提交。");
                }
                String checkResult = CheckMainData(mainEntity);
                if (!StringUtils.isEmpty(checkResult)) {
                    return JsonResult.error(checkResult);
                }
                if (entity != null) {
                    Map<String, Object> param = new HashMap<>();
                    param.put("wxtbh", mainEntity.getWxtbh());
                    param.put("wxt_id", mainEntity.getWxtId());
                    formtableMain12083Mapper.deleteByMap(param);
                    param.clear();
                    param.put("parent_id", entity.getId());
                    formtableMain12083Dt1Mapper.deleteByMap(param);
                }
                formtableMain12083Mapper.insert(mainEntity);
                for (FormtableMain12083Dt1 item : dto.getFormtableDetails()) {
                    item.setParentId(mainEntity.getId());
                    formtableMain12083Dt1Mapper.insert(item);
                }
                return JsonResult.success("数据提交成功。");
            } else {
                return JsonResult.error("提交数据出错，请检查提交数据格式。");
            }
        } catch (Exception ex) {
            return JsonResult.error(ex.getMessage());
        }
    }


    /**
     * 判断外系统编号是否已经维护
     * */
    private boolean isExistsWxtbh(String wxtbh)
    {
        List<DictData> dictData = dictDataService.list(new QueryWrapper<DictData>().eq("code",wxtbh));

        return dictData.size()>0?true:false;
    }
    @Override
    @SpecifyDataSource(value = DataSourceType.BIP)
    public JsonResult uploadMultiFile(MultipartFile[] fileHead,MultipartFile[] fileBody, String documentId,String getFromFile){
        return this.uploadFileDt(fileHead,fileBody,documentId,getFromFile,null);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.BIP)
    public JsonResult uploadFileDt(MultipartFile[] fileHead,MultipartFile[] fileBody, String documentId,String getFromFile,String dtWxtbh){
        String fileName = "";
        StringBuilder sb = new StringBuilder();
        //判断外部系统编号是否已经开通
        DynamicDataSource.setDataSource("system");
        List<DictData> dictDatas = dictDataService.list(new QueryWrapper<DictData>().eq("code",getFromFile));
        boolean existsWxtbh = dictDatas.size()>0?true:false;
        if(!existsWxtbh)
        {
            return JsonResult.error("外系统编号："+getFromFile+" 未开通，无法上传附件");
        }
        //获取外系统，是否允许先上传附件
        DictData dictData = dictDatas.get(0);
        String uploadFlag = StringUtils.isEmpty(dictData.getNote())?"N":dictData.getNote();
        DynamicDataSource.setDataSource("bip");
        FormtableMain12083ListVo entity = formtableMain12083Mapper.GetEntity(documentId,getFromFile);
        //判断表单数据是否已经提交,若允许先上传附件则跳过检查
        if(ObjectUtil.isNull(entity)){
            if("N".equals(uploadFlag)) {
                return JsonResult.error("外系统编号：" + documentId + " 外系统ID:" + getFromFile + "表单数据未提交，无法上传附件。");
            }
        } else {
            //判断OA是否已经同步
//            if ("1".equals(entity.getFtriggerflag())) {
//                return JsonResult.error("外系统编号：" + documentId + " OA流程ID:" + entity.getRequestid() + ",OA系统已读取，无法再次上传附件。");
//            }
        }

        if(fileHead.length==0 || fileBody.length==0) {
            return JsonResult.error("上传失败:未选择表头或表体的上传文件。表头附件数:"+fileHead.length+",表体附件数:"+fileBody.length);
        }
        if(StringUtils.isEmpty(documentId) || StringUtils.isEmpty(getFromFile))
        {
            return JsonResult.error("上传失败:外系统编号或外系统ID为空。外系统ID:"+getFromFile+",外系统编号:"+documentId);
        }
        for (MultipartFile file : fileHead) {
            String fileDesc = file.getOriginalFilename();
            String suffixName = fileDesc.substring(fileDesc.lastIndexOf("."));//拿到后缀名
            GuidCreator myGUID = new GuidCreator();
            fileName = myGUID.createNewGuid(GuidCreator.FormatString);
            fileName = fileName + suffixName;
            if (org.springframework.util.StringUtils.isEmpty(fileName)) {
                //return JsonResult.success("上传文件为空");
                continue;
            }
            File filePath = new File("");
            //当前项目下路径+静态资源实际存储路径
            String path = filePath.getAbsolutePath();
            String templatePath = path + UploadFileConfig.uploadFolder;
            templatePath = templatePath.replace('\\', '/');
            templatePath+=getFromFile;
            if(!templatePath.endsWith("/"))
            {
                templatePath+="/";
            }
            templatePath += dtWxtbh == null ? documentId + "/head" : documentId + "/head" + "/" + dtWxtbh;

            File dests = new File(templatePath);
            File dest = new File(dests, fileDesc);
            //文件上传-覆盖
            try {
                // 检测是否存在目录
                if (!dests.exists()) {
                    dests.mkdirs();
                }
                // getParentFile获取上一级
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                file.transferTo(dest);



                //插入数据到file_info-----------------
//                    List<SuppfileInfo> list = getFileInfoListByWhere(documentId, fileName, getFromFile);
//                    if (list.size() <= 0) {
//                        SuppfileInfo fi = new SuppfileInfo();
//                        String fileUrl = UploadFileConfig.accessFilePath + fileName;
//                        fi.setFilePath(fileUrl);//获取配置文件中的相对路径
//                        fi.setFileName(fileName);//guid+后缀名
//                        fi.setFileDesc(fileDesc);//文件描述=文件名
//                        fi.setDocumentId(documentId);//关联主表id
//                        fi.setGetFromFile(getFromFile); //附件主表
//                        edit(fi);
//                    }
                //---------------------------------------------

            } catch (Exception e) {
                sb.append("[" + fileName + "]上传失败：" + e.getMessage());
            }
        }

        for (MultipartFile file : fileBody) {
            String fileDesc = file.getOriginalFilename();
            String suffixName = fileDesc.substring(fileDesc.lastIndexOf("."));//拿到后缀名
            GuidCreator myGUID = new GuidCreator();
            fileName = myGUID.createNewGuid(GuidCreator.FormatString);
            fileName = fileName + suffixName;
            if (org.springframework.util.StringUtils.isEmpty(fileName)) {
                //return JsonResult.success("上传文件为空");
                continue;
            }
            File filePath = new File("");
            //当前项目下路径+静态资源实际存储路径
            String path = filePath.getAbsolutePath();
            String templatePath = path + UploadFileConfig.uploadFolder;
            templatePath = templatePath.replace('\\', '/');
            templatePath+=getFromFile;
            if(!templatePath.endsWith("/"))
            {
                templatePath+="/";
            }
            templatePath += dtWxtbh == null ? documentId + "/body" : documentId + "/body" + "/" + dtWxtbh;

            File dests = new File(templatePath);
            File dest = new File(dests, fileDesc);
            //文件上传-覆盖
            try {
                // 检测是否存在目录
                if (!dests.exists()) {
                    dests.mkdirs();
                }
                // getParentFile获取上一级
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                file.transferTo(dest);

                //插入数据到file_info-----------------
//                    List<SuppfileInfo> list = getFileInfoListByWhere(documentId, fileName, getFromFile);
//                    if (list.size() <= 0) {
//                        SuppfileInfo fi = new SuppfileInfo();
//                        String fileUrl = UploadFileConfig.accessFilePath + fileName;
//                        fi.setFilePath(fileUrl);//获取配置文件中的相对路径
//                        fi.setFileName(fileName);//guid+后缀名
//                        fi.setFileDesc(fileDesc);//文件描述=文件名
//                        fi.setDocumentId(documentId);//关联主表id
//                        fi.setGetFromFile(getFromFile); //附件主表
//                        edit(fi);
//                    }
                //---------------------------------------------

            } catch (Exception e) {
                sb.append("[" + fileName + "]上传失败：" + e.getMessage());
            }
        }
        if(StringUtils.isEmpty(sb.toString())) {
            return JsonResult.success("附件上传成功,表头附件数:" + fileHead.length+",表头附件数:" + fileBody.length);//上传成功,文件名以逗号隔开
        }
        else
        {
            return JsonResult.error(sb.toString());
        }
    }


    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    public Object getInfo(Serializable id) {
        FormtableMain12083 entity = (FormtableMain12083) super.getInfo(id);
        // 返回视图Vo
        FormtableMain12083InfoVo formtableMain12083InfoVo = new FormtableMain12083InfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, formtableMain12083InfoVo);
        return formtableMain12083InfoVo;
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult edit(FormtableMain12083 entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
        } else {
            entity.setCreateTime(DateUtils.now());
        }
        return super.edit(entity);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult delete(FormtableMain12083 entity) {
        entity.setMark(0);
        return super.delete(entity);
    }

}